package cn.sxy.mybatis.executor.statement;

import cn.sxy.mybatis.executor.Executor;
import cn.sxy.mybatis.executor.parameter.ParameterHandler;
import cn.sxy.mybatis.mapping.BoundSql;
import cn.sxy.mybatis.mapping.MappedStatement;
import cn.sxy.mybatis.session.ResultHandler;
import cn.sxy.mybatis.session.RowBounds;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

public class PreparedStatementHandler extends BaseStatementHandler {

    public PreparedStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
        super(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql);
    }


    @Override
    protected Statement instantiateStatement(Connection connection) throws SQLException {
        String sql = boundSql.getSql();
        return connection.prepareStatement(sql);
    }

    @Override
    public void parameterize(Statement statement) throws SQLException {
//        PreparedStatement ps = (PreparedStatement) statement;
//        //只有PreparedStatement才有set方法， ((Object[]) parameterObject)[0]值为1
//        //参数1---表示设置道第一个占位符？上
//        ps.setLong(1, Long.parseLong(((Object[]) parameterObject)[0].toString()));

        //开启动态解析参数
        parameterHandler.setParameter((PreparedStatement)statement);

    }

    @Override
    public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
        PreparedStatement ps = (PreparedStatement) statement;
        ps.execute();
        return resultSetHandler.<E> handleResultSets(ps);
    }

}
